<template>
  <a-card :bordered="false">

    <!-- 操作按钮区域 -->
    <div class="table-operator" :md="24" :sm="24" style="margin: 0px 0px 20px 0px">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :data="{'storeId': this.queryParam.mainId}"
        :action="importExcelUrl" @change="handleImport">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-button type="primary" icon="download" @click="handleExportXls('经销商可售物料模板.xlsx')">下载模板</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys.length
        }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
            <a @click="update(record)" style="margin-left: 8px;margin-right: 20px; ">编辑</a>
           <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <StmStoreProduct ref="stmStoreProduct" @selectFinished="selectOK" @updateCompleted="loadData" />
  </a-card>
</template>

<script>
import StmStoreProduct from './modules/StmStoreProduct'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {getAction, postAction, deleteAction, downFile} from '@/api/manage'

export default {
  name: 'StmStoreProductListJXV2',
  mixins: [JeecgListMixin],
  components: {
    StmStoreProduct
  },
  data() {
    return {
      importExcelUrl:`${window._CONFIG['domianURL']}/stm/stmStoreInfo/importPmsSkuStockExcel`,
      description: '信息',
      // 表头
      columns: [
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productId_dictText'
        },
        {
          title: '货号',
          align: 'center',
          dataIndex: 'productSn'
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'skuCode'
        }, {
          title: '价格',
          align: 'center',
          dataIndex: 'price'
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          width: 200,
          scopedSlots: {customRender: 'action'}
        }],
      url: {
        list: '/stm/stmStoreInfo/listPmsSkuStockByStoreId',
        delete: '/stm/stmStoreInfo/deleteSkuById',
        deleteBatch: '/stm/stmStoreInfo/deleteBatchSkuByIds',
        add: '/stm/stmStoreInfo/addStmStoreRelation',
        exportXls: '/stm/stmStoreInfo/download'
      }
    }
  },
  methods: {
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()
      getAction(this.url.list, {
        storeId: params.mainId
        , pageNo: this.ipagination.current, pageSize: this.ipagination.pageSize
      }).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        } else {
          this.dataSource = null
        }
      })
    },
    getMain(mainId) {
      this.queryParam.mainId = mainId
      this.loadData(1)
    },
    handleAdd: function () {
      if (this.queryParam.mainId) {
        this.$refs.stmStoreProduct.brandCategory = 2;
        this.$refs.stmStoreProduct.add(this.queryParam.mainId);
        this.$refs.stmStoreProduct.title = "新增";
      } else {
        this.$message.warning('请选择一条数据');
      }
    },
    update: function (record) {
      this.$refs.stmStoreProduct.edit(record);
      this.$refs.stmStoreProduct.title = "编辑";
    },
    handleDelete: function (id) {
      if(id==null || id=="") {
        this.$message.warning('请选择一条数据');
        return;
      }
      let that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    batchDel: function (id) {

    },
    selectOK(data) {
      let params = {};
      params.storeId = this.queryParam.mainId;
      params.brandCategory = 2;
      params.salesIdList = [];
      for (var a = 0; a < data.length; a++) {
        params.salesIdList.push(data[a].id);
      }
      console.log(params);
      postAction(this.url.add, params).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
          this.loadData(1)
        } else {
          this.$message.warning(res.message);
        }
      })
    },
    handleExportXls(fileName) {
      downFile(this.url.exportXls, null).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName)
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    handleImport(info){
      if (!this.queryParam.mainId) {
        this.$message.warning('请选择一条数据');
        return;
      }
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span><br/>
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `);
      }
    }
  }
}
</script>
<style scoped>
.ant-card {
  margin-left: -30px;
  margin-right: -30px;
}
</style>

